import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import 'package:hotfil_pub_web/lang/translation_service.dart';
import 'package:hotfil_pub_web/routes/app_pages.dart';
import 'package:hotfil_pub_web/shared/loading.dart';

import '../app_exceptions.dart';
import 'package:get/get.dart';

import '../sputils.dart';

/// 请求处理拦截器
class RequestInterceptor extends Interceptor {
  @override
  onRequest(options, handle) {
    debugPrint(
        '======================\n*** Request *** \nData:\n ${options.data.toString()} \nQuery:\n ${options.queryParameters.toString()} \n======================');
    // // 设置cookie
    // var cookie = SpUtil.getStringList('cookie');登录时保存cookie

    // if (options.path != 'api/auth/login' &&
    //     cookie != null &&
    //     cookie.length > 0) {
    //   options.headers['cookie'] = cookie;//这里就是除了登录的情况其他都加cookie
    // }

    options.headers['lang'] = TranslationService.isENLang ? 'en' : 'tw';
    var token = SpUtil().getStr('token');
    if (token != null) {
      options.headers['authorization'] = 'Bearer $token';
    }
    //
    // if (options.data?.runtimeType == FormData) {
    //   options.headers['content-type'] = 'multipart/form-data';//FormData这种情况改content-type
    // }

    // // 加载动画----这个就是请求页面时的那个loading窗 --处理逻辑 我是用options?.data['showLoading']或options?.queryParameters['showLoading'],
    //就是我们在传参的时候多加一个参数，这个因为前人就这样做的，也跟后端约定的，后端见showLoading不做处理。这样不是很好，反正options是有其他字段加的

    if (true == options.extra['showLoading']) {
      startLoading();
    }

    handle.next(options);
    //return super.onRequest(options);
  }

  @override
  onResponse(response, handle) {
    stopLoading();
    handle.next(response);
  }

  //
  @override
  onError(err, handle) {
    stopLoading();

    AppException appException = AppException.create(err);
    err.error = appException;
    if (err.response?.statusCode != null && err.response?.statusCode == 401) {
      Get.offAndToNamed(Routes.PASS_LOGIN);
    }

    return super.onError(err, handle);
  }
}
